package com.yoshino.book.controller;

import com.yoshino.book.pojo.Cart;
import com.yoshino.book.pojo.User;
import com.yoshino.book.service.CartItemService;
import com.yoshino.book.service.UserService;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class UserController {

    private UserService userService;
    private CartItemService cartItemService;
//    private BookService bookService;

    public String login(String uname, String pwd, HttpSession session){

        User user = userService.login(uname, pwd);
//        List<Book> bookList = bookService.getBookList();
        if (user != null){
            Cart cart = cartItemService.getCart(user);
            user.setCart(cart);

            session.setAttribute("currUser", user);
            return "redirect:book.do";
        }
        return "user/login";
    }

    public String cancel(HttpSession session){
        session.setAttribute("currUser",null);
        return "redirect:book.do";
    }

    public String regist(String verifyCode, String uname, String pwd, String email, HttpSession session, HttpServletResponse response) throws IOException {
        //二维码功能包导入问题
        /*
        Object kaptchaCodeobj = session.getAttribute("KAPTCHA_SESSION_KEY");
        if (kaptchaCodeobj==null || !verifyCode.equals(kaptchaCodeobj)){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println("<script language='javascript'>alert('验证码不正确!');window.location.href='http://localhost:8080/page.do?operate=page&page=user/regist';</script>");
//            return "user/regist";
            return null;
        }else {
            if (verifyCode.equals(kaptchaCodeobj)){
                userService.regist(new User(uname,pwd,email,0));
                return "user/login";
            }
        }*/

        userService.regist(new User(uname, pwd, email, 0));


        return "user/login";
    }

    public String ckUname(String uname){
        User user = userService.getUser(uname);
        if (user != null){
            //用户名已经被占用，不可注册
            return "json:{'uname':'1'}";
            //return "ajax:1";
        }else {
            //用户名未被注册
            return "json:{'uname':'0'}";
            //return "ajax:0";
        }
    }
}
